package com.lyf.service.impl;

import com.lyf.entity.Order;
import com.lyf.entity.Stock;
import com.lyf.entity.User;
import com.lyf.mapper.OrderMapper;
import com.lyf.mapper.StockMapper;
import com.lyf.mapper.UserMapper;
import com.lyf.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService{

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public int kill(Integer id) {
        //校验redis中的秒杀商品是否超时
        if(!stringRedisTemplate.hasKey("kill" + id))
            throw new RuntimeException("当前商品的抢购活动已经结束");

        //校验库存
        Stock stock = checkStock(id);
        //扣除库存
        updateStock(stock);
        //创建订单
        return createOrder(stock);
    }

    @Override
    public String getMd5(Integer id, Integer userid) {
        //验证用户合法性：是否存在用户信息
        User user = userMapper.findUserById(userid);
        if(user == null) throw new RuntimeException("用户信息不存在!");
        log.info("用户信息：[()]", user.toString());

        //验证商品合法性：是否存在商品信息
        Stock stock = stockMapper.checkStock(id);
        if(stock == null) throw new RuntimeException("商品信息不存在！");
        log.info("商品信息：[()]", stock.toString());

        //生成hashkey
        String hashKey = "KEY_" + userid + "_" + id;
        //生成随机盐
        String key = DigestUtils.md5DigestAsHex((userid + "_" + id + "!Q*js#").getBytes());
        stringRedisTemplate.opsForValue().set(hashKey,key,120, TimeUnit.SECONDS);
        log.info("redis写入：[{}][{}]",hashKey,key);

        return key;
    }

    @Override
    public int kill(Integer id, Integer userid, String md5) {
//        //校验redis中的秒杀商品是否超时
//        if(!stringRedisTemplate.hasKey("kill" + id))
//            throw new RuntimeException("当前商品的抢购活动已经结束");
        //验证签名
        String hashKey = "KEY_" + userid + "_" + id;    //拼接redis的key
        String key = stringRedisTemplate.opsForValue().get(hashKey);
        if(key == null) throw new RuntimeException("没有携带前面，请求不合法！");
        if(!key.equals(md5)) throw new RuntimeException("当前请求不合法");
        //校验库存
        Stock stock = checkStock(id);
        //扣除库存
        updateStock(stock);
        //创建订单
        return createOrder(stock);
    }

    //校验库存
    private Stock checkStock(Integer id) {
        Stock stock = stockMapper.checkStock(id);
        if(stock.getCount().equals(stock.getSale())){
            throw new RuntimeException("库存不足");
        }
        return stock;
    }
    //扣除库存
    private void updateStock(Stock stock) {
        //在sql层面完成 销量+1 和 版本号+1；并且根据商品id 和 版本号同时查询商品
        int updataRows = stockMapper.updateStock(stock);
        if(updataRows == 0)
            throw new RuntimeException("抢购失败，请重试");
    }
    //创建订单
    private Integer createOrder(Stock stock){
        Order order = new Order();
        order.setSid(stock.getId());
        order.setName(stock.getName());
        order.setCreatTime(new Date());
        orderMapper.createOrder(order);
        return order.getId();
    }

}
